/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.core.wicket.panel.paging;

import java.util.ArrayList;
import java.util.Iterator;

import com.eelpo.cmmp.core.constants.SystemConstants;
import com.eelpo.common.util.BlankUtils;

import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;

/**
 * <pre>
 * 
 * 动态分页数据提供者
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class DynamicPagingSortableDataProvider<T extends ISort> extends SortableDataProvider<T> {

	protected T parameter;
	protected IDynamicPaing<T> dynamicPaing;
	private static final long serialVersionUID = -8847322844877279397L;

	public DynamicPagingSortableDataProvider(IDynamicPaing<T> dynamicPaing, T parameter) {
		this.parameter = parameter;
		this.dynamicPaing = dynamicPaing;

	}

	/**
	 * 代理Iterator方法
	 */
	@Override
	public Iterator<? extends T> iterator(int i, int j) {

		if (!BlankUtils.isBlank(getSort())) {
			if (getSort().isAscending()) {
				parameter.setSort(getSort().getProperty(), SystemConstants.SORT_ASC);
			} else {
				parameter.setSort(getSort().getProperty(), SystemConstants.SORT_DESC);
			}
		}

		try {
			return dynamicPaing.iterator(parameter, i, j);
		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<T>(1).iterator();
		}
	}

	/**
	 * 代理model方法
	 */
	@Override
	public IModel<T> model(T obj) {
		return dynamicPaing.model(obj);
	}

	/**
	 * 代理size方法
	 */
	@Override
	public int size() {
		try {
			return dynamicPaing.totalRows(parameter);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
}
